//
//  SSAddressViewController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/3/7.
//

import UIKit

import SwiftyJSON

class SSAddressViewController: UIViewController {
    
    @IBOutlet weak var saveBtn: UIButton!
    var selectedBtn:UIButton?
    var manBtn:UIButton = UIButton()
    var womanBtn:UIButton = UIButton()
    var addressTextF:UITextField = UITextField()
    var houseNoTextF:UITextField = UITextField()
    var zipCodeTextF:UITextField = UITextField()
    var contactTextF:UITextField = UITextField()
    var phoneNTextF:UITextField = UITextField()
    var isModify:Bool = false
    var address:SSAddress = SSAddress()
    var addressListController: SSAddressListController?     // 闭包
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "修改地址"

        setupUIS()
        self.addressTextF.text = address.address
        self.houseNoTextF.text = address.houseNo
        self.zipCodeTextF.text = address.zip
        self.contactTextF.text = address.contact
        self.phoneNTextF.text = address.contactPhone
        if address.sex == "0" {
            self.womanBtn.isSelected = true
            self.selectedBtn = self.womanBtn
        }else{
            self.manBtn.isSelected = true
            self.selectedBtn = self.manBtn
        }
  
    }
    
    @objc func btnTapped(_ button:UIButton){
        if button == self.selectedBtn {
            return
        }
        button.isSelected = !button.isSelected
        self.selectedBtn?.isSelected = !(self.selectedBtn?.isSelected ?? true)
        self.selectedBtn = button
        print("\(button.tag)")
    }
    
    func setupUIs(title:String, describe:String,index:Int) ->UIView {
        let bgView = UIView()
        bgView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 74)
        
        let titleLab = UILabel()
        titleLab.text = title
        titleLab.frame = CGRect(x: 16, y: 16, width: 200, height: 20)
        titleLab.font = UIFont.systemFont(ofSize: 14)
        bgView.addSubview(titleLab)
        
        let textF =  UITextField()
        textF.frame = CGRect(x: 16, y: titleLab.frame.maxY + 12, width: 200, height: 20)
        textF.placeholder = describe
        textF.font = UIFont.systemFont(ofSize: 14)
        bgView.addSubview(textF)
        textF.addTarget(self, action: #selector(textFieldDidEndEditing), for: .editingChanged)
        textF.tag = index + 100
        textF.keyboardType = .numberPad
        if index == 0 {
            textF.keyboardType = .default
            addressTextF = textF
        }else if(index == 1){
            houseNoTextF = textF
        }else if(index == 2){
            zipCodeTextF = textF
        }else if(index == 3){
            textF.keyboardType = .default
            contactTextF = textF
        }else if(index == 4){
            phoneNTextF = textF
        }
        
        let line = UIView()
        line.frame = CGRect(x: 16, y: bgView.frame.height - 1, width: ScreenWidth - 16*2, height: 1)
        line.backgroundColor = UIColor.lineColor
        bgView.addSubview(line)
        return bgView
    }
   
    @IBAction func saveAction(_ sender: Any) {

        if (addressTextF.text?.count == 0) {
            view.makeToast("地址不能为空！")
            return
        }
        if (houseNoTextF.text?.count == 0) {
            view.makeToast("门牌号不能为空！")
            return
        }
        if (zipCodeTextF.text?.count == 0) {
            view.makeToast("邮编不能为空！")
            return
        }
        if !Validate.ZIP(zipCodeTextF.text ?? "").isRight {
            view.makeToast("请输入正确邮编！")
            return
        }
        if (contactTextF.text?.count == 0) {
            view.makeToast("联系人不能为空！")
            return
        }
        if selectedBtn == nil {
            view.makeToast("请选择联系人性别！")
            return
        }
        // 校验手机号
        if (phoneNTextF.text?.count == 0) {
            view.makeToast("手机号不能为空！")
            return
        }
        if !Validate.phoneNum(phoneNTextF.text ?? "").isRight {
            view.makeToast("请输入正确手机号！")
            return
        }
       
        saveAddressRequest()
    }
   
}


extension SSAddressViewController {

    
    //MARK: -network
    func saveAddressRequest() {
        let zip = zipCodeTextF.text
        let contact = contactTextF.text
        var params = [
            "phoneNo": kUserPhone,
            "address": addressTextF.text!,
            "houseNo": houseNoTextF.text!,
            "zip": zip!,
            "contact": contact!,
            "contactPhone": phoneNTextF.text!,
            "sex":"\(String(describing: selectedBtn!.tag))",
                ] as! [String:AnyObject]
        if self.address.id.count > 0 {
            params["id"] = address.id as AnyObject
        }
        
        address.zip = zipCodeTextF.text!
        address.contact = contactTextF.text!
        address.address = addressTextF.text!
        address.houseNo = houseNoTextF.text!
        address.contactPhone = phoneNTextF.text!
        address.sex = "\(String(describing: selectedBtn!.tag))"
        
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.updateUserAddress_URL, parameters: params) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                
                let json = JSON(parseJSON: result!)
                let retCode = json["retCode"].stringValue
                let retMsg = json["data"].stringValue
                let data = json["retMsg"].stringValue
                if(retCode == "0000"){
                    //我的地址进入修改完成跳转到push页面
                    //订单页进入修改完成跳转到订单页面
                    if (self.addressListController?.addressListClosure != nil)  {
                        self.addressListController?.addressListClosure!(self.address)
                        self.navigationController?.popToViewController((self.addressListController?.userOrderController)!, animated: true)
                        dissmissToTast(msg: "地址保存成功!")
                    }else{
                        dissmissToTast(msg: "地址保存成功!")
                        self.navigationController?.popViewController(animated: true)
                    }
                }else{
                    dissmissToTast(msg: "\(data)")
                }
  
            }
        }
    }
}


/// 文本输入按钮状态改变
extension SSAddressViewController {
    @objc func textFieldDidEndEditing(_ textField: UITextField) {
        print("\(String(describing: textField.text))")
        
    }
}

///
extension SSAddressViewController {
    func setupUIS() {
        saveBtn.layer.masksToBounds = true
        saveBtn.layer.cornerRadius = 6

        let titles:Array<String> = ["地址","门牌","邮编","联系人","电话"]
        let describes:Array<String> = ["请选择地址","请填写门牌号","请填写邮编","请填写联系人姓名","请填写联系人电话"]
        var y:CGFloat = getNavHeight()

        for (i, title) in titles.enumerated() {
            let view0 = setupUIs(title: title, describe: describes[i],index: i)
            view.addSubview(view0)
            view0.frame = CGRect(x: 0, y: y, width: ScreenWidth, height: 74)
            y = view0.frame.maxY
            if i == 2 {
                let sectionView = UIView()
                sectionView.frame = CGRect(x: 0, y: y + 2, width: ScreenWidth, height: 6)
                sectionView.backgroundColor = UIColor.init(hex: "#E5E5E5")
                y = sectionView.frame.maxY
                view.addSubview(sectionView)
            }
            if i == 3 {
                let btn = UIButton()
                btn.frame = CGRect(x: ScreenWidth - 16 - 50, y: 47, width: 50, height: 20)
                btn.tag = 100
    //                btn.backgroundColor = UIColor.blue
                btn.setTitleColor(UIColor.init(hex: "#1A1A1A"), for: .normal)
                btn.setTitle(" 女士", for: .normal)
                btn.setImage(UIImage(named: "Rectangle-16*16"), for: .normal)
                btn.setImage(UIImage(named: "Radio-Selected-16*16"), for: .selected)
                btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                btn.titleLabel?.textColor = UIColor.init(hex: "#1A1A1A")?.withAlphaComponent(0.6)
                self.womanBtn = btn
                btn.tag = 0
                view0.addSubview(btn)
                btn.addTarget(self, action:#selector(btnTapped(_:)), for:.touchUpInside)

                let btn1 = UIButton()
                btn1.frame = CGRect(x: ScreenWidth - 16 - 50 - 20 - 50, y: 47, width: 50, height: 20)
    //                btn.backgroundColor = UIColor.blue
                btn1.setTitleColor(UIColor.init(hex: "#1A1A1A"), for: .normal)
                btn1.tag = 101
                self.manBtn = btn
                btn1.setTitle(" 男士", for: .normal)
                btn1.setImage(UIImage(named: "Rectangle-16*16"), for: .normal)
                btn1.setImage(UIImage(named: "Radio-Selected-16*16"), for: .selected)
                btn1.titleLabel?.font = UIFont.systemFont(ofSize: 14)
                btn1.titleLabel?.textColor = UIColor.init(hex: "#1A1A1A")?.withAlphaComponent(0.6)
                btn1.tag = 1
                view0.addSubview(btn1)
                btn1.addTarget(self, action:#selector(btnTapped(_:)), for:.touchUpInside)

            }
        }
    }
}



enum Validate {
    case email(_: String)
    case phoneNum(_: String)
    case carNum(_: String)
    case username(_: String)
    case password(_: String)
    case nickname(_: String)
    case URL(_: String)
    case IP(_: String)
    case ZIP(_: String)
    var isRight: Bool {
        var predicateStr:String!
        var currObject:String!
        switch self {
        case let .email(str):
            predicateStr = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
            currObject = str
        case let .phoneNum(str):
            predicateStr = "^(?:\\+?61)?(?:\\(0\\)[23478]|\\(?0?[23478]\\)?)\\d{8}$"
            currObject = str
        case let .carNum(str):
            predicateStr = "^[A-Za-z]{1}[A-Za-z_0-9]{5}$"
            currObject = str
        case let .username(str):
            predicateStr = "^[A-Za-z0-9]{6,20}+$"
            currObject = str
        case let .password(str):
            predicateStr = "^[a-zA-Z0-9]{6,20}+$"
            currObject = str
        case let .nickname(str):
            predicateStr = "^[\\u4e00-\\u9fa5]{4,8}$"
            currObject = str
        case let .URL(str):
            predicateStr = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
            currObject = str
        case let .IP(str):
            predicateStr = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
            currObject = str
        case let .ZIP(str):
            predicateStr = "^(\\d{4})$"
            currObject = str
        }
        let predicate =  NSPredicate(format: "SELF MATCHES %@" ,predicateStr)
        return predicate.evaluate(with: currObject)
    }
}
